
import java.io.BufferedReader;
import java.io.FileReader;

import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;
import org.neo4j.graphdb.index.IndexHits;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import org.neo4j.tooling.GlobalGraphOperations;


public class GraphCreator {

	public static RelationshipType LINKED = DynamicRelationshipType.withName("linked");
	
	public static void createGraph(EmbeddedGraphDatabase db, Transaction tx) throws Exception{
		
		cleanUp(db);
		try{
			Index<Node> index = db.index().forNodes("nodes");
			BufferedReader input = new BufferedReader(new FileReader("graph.txt"));
			
			String line = input.readLine();
			String[] tokens = line != null ? line.split(" ") : null;
			while (tokens != null && tokens.length == 3){
				Node currentNode = index.get("name", tokens[0]).getSingle();
				Node linkedNode = index.get("name", tokens[2]).getSingle();
				if (currentNode == null){
					currentNode = db.createNode();
					currentNode.setProperty("name", tokens[0]);
					index.add(currentNode, "name", tokens[0]);
				}
				if (linkedNode == null){
					linkedNode = db.createNode();
					linkedNode.setProperty("name", tokens[2]);
					index.add(linkedNode, "name", tokens[2]);
				}
				Relationship relationship = currentNode.createRelationshipTo(linkedNode, LINKED);
				relationship.setProperty("distance", Integer.valueOf(tokens[1]));
//				System.out.println(currentNode.getProperty("name") + " ["+relationship.getProperty("distance")+"]> "+linkedNode.getProperty("name"));
				
				line = input.readLine();
				tokens = line != null ? line.split(" ") : null;
			}
			tx.success();
			
		}catch (Exception e){
			tx.failure();
			throw e;
		}finally{
			tx.finish();
		}
	}
	
	private static void cleanUp(EmbeddedGraphDatabase db){
		Index<Node> index = db.index().forNodes("nodes");
		for (Node node : GlobalGraphOperations.at(db).getAllNodes()) {
			for (Relationship relationship : node.getRelationships()) {
				relationship.delete();
			}
			index.remove(node);
			node.delete();
		}
	}
	
}
